<template>
  <div class="container">
    <div class="header">
      <h1>会员管理</h1>
      <div class="actions">
        <el-button type="primary" @click="showAddDialog">新增会员</el-button>
        <el-button type="success" @click="showImportDialog">从Excel导入会员</el-button>
      </div>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="会员名称">
          <el-input v-model="searchForm.name" placeholder="请输入会员名称" clearable />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="memberList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="会员名称" />
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="points" label="积分" />
        <el-table-column label="头像" width="100">
          <template #default="scope">
            <div class="avatar-preview-container">
              <img
                style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"
                :src="scope.row.avatar || ''"
                :onerror="'this.style.display=\'none\'; this.nextElementSibling.style.display=\'flex\''"
              />
              <el-avatar
                v-if="!scope.row.avatar"
                :size="40"
                :icon="UserFilled"
                style="display: none;">
              </el-avatar>
              <el-button
                class="preview-btn"
                type="primary"
                size="small"
                circle
                @click="previewImage(scope.row.avatar)"
                :disabled="!scope.row.avatar">
                <el-icon><ZoomIn /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" :formatter="formatDate" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="editMember(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDeleteMember(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 会员表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增会员' : '编辑会员'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="memberForm" :rules="rules" ref="memberFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="memberForm.name" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="memberForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="memberForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="memberForm.points" :min="0" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader-component"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              accept="image/jpeg,image/png,image/gif"
            >
              <div class="avatar-container">
                <img
                  v-if="memberForm.avatar"
                  :src="memberForm.avatar"
                  class="avatar-preview"
                />
                <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
              </div>
            </el-upload>
            <div v-if="memberForm.avatar" class="preview-actions">
              <el-button 
                type="primary" 
                @click="previewImage(memberForm.avatar)"
                size="small">
                <el-icon><ZoomIn /></el-icon> 预览
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog title="导入会员" v-model="importDialogVisible" width="400px">
      <div class="template-download">
        <el-link type="primary" @click="downloadTemplate">
          <el-icon><download /></el-icon>
          下载Excel导入模板
        </el-link>
      </div>
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件(.xlsx/.xls)
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :disabled="!excelFile">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="头像预览" width="400px" append-to-body center>
      <div class="image-preview-dialog">
        <el-image
          style="width: 100%;"
          :src="previewImageUrl"
          fit="contain"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, UploadFilled, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { listMembers, addMember, updateMember, deleteMember, importMembers, downloadExcelTemplate } from '@/api/member'
import { uploadFile } from '@/api/upload'

const loading = ref(false)
const memberList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const importDialogVisible = ref(false)
const excelFile = ref(null)
const memberFormRef = ref(null)
const avatarFile = ref(null)
const previewVisible = ref(false)
const previewImageUrl = ref('')

const searchForm = reactive({
  name: '',
  phone: ''
})

const memberForm = reactive({
  id: null,
  name: '',
  phone: '',
  address: '',
  points: 0,
  avatar: '',
  openid: ''
})

const rules = {
  name: [
    { required: false, message: '请输入会员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (row, column) => {
  const dateStr = row[column.property]
  if (!dateStr) return '-'
  return dateStr.replace('T', ' ').substring(0, 16)
}

// 显示新增对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  Object.keys(memberForm).forEach(key => {
    if (key !== 'points') {
      memberForm[key] = ''
    } else {
      memberForm[key] = 0
    }
  })
  dialogVisible.value = true
}

// 编辑会员
const editMember = (row) => {
  dialogType.value = 'edit'
  Object.keys(memberForm).forEach(key => {
    memberForm[key] = row[key]
  })
  dialogVisible.value = true
}

// 确认删除会员
const confirmDeleteMember = (row) => {
  ElMessageBox.confirm(
    `确定要删除会员 ${row.name || '未命名'} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    handleDeleteMember(row.id)
  }).catch(() => {})
}

// 处理删除会员
const handleDeleteMember = async (id) => {
  try {
    await deleteMember(id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除会员失败', error)
    ElMessage.error('删除失败')
  }
}

// 处理头像选择，只预览不上传
const handleAvatarChange = (file) => {
  avatarFile.value = file.raw

  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    // 显示本地预览图
    memberForm.avatar = e.target.result
  }
  reader.readAsDataURL(avatarFile.value)
}

// 提交表单
const submitForm = async () => {
  if (!memberFormRef.value) return

  await memberFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 如果选择了新头像，先上传头像
        if (avatarFile.value) {
          const res = await uploadFile(avatarFile.value, 'avatar')
          if (res && res.code === 200) {
            memberForm.avatar = `http://localhost:8080/api`+res.message // 后端返回的图片URL
            ElMessage.success('头像上传成功')
          } else {
            throw new Error(res.message || '头像上传失败')
          }
        }

        if (dialogType.value === 'add') {
          await addMember(memberForm)
          ElMessage.success('添加成功')
        } else {
          await updateMember(memberForm)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('操作失败', error)
        ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 显示导入对话框
const showImportDialog = () => {
  excelFile.value = null
  importDialogVisible.value = true
}

// 处理文件变化
const handleFileChange = (file) => {
  excelFile.value = file.raw
}

// 提交导入
const submitImport = async () => {
  if (!excelFile.value) {
    ElMessage.warning('请选择文件')
    return
  }

  try {
    // 显示加载状态
    loading.value = true
    await importMembers(excelFile.value)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('导入失败', error)
    ElMessage.error('导入失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.phone = ''
  currentPage.value = 1
  fetchData()
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      phone: searchForm.phone || undefined
    }

    const res = await listMembers(params)
    if (res && res.data) {
      memberList.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取会员数据失败', error)
    ElMessage.error('获取会员数据失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 下载Excel模板
const downloadTemplate = async () => {
  try {
    const response = await downloadExcelTemplate()
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = '会员导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败', error)
    ElMessage.error('下载模板失败')
  }
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      font-size: 24px;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .el-upload {
    width: 100%;
  }

  .template-download {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
  }

  .avatar-preview-container {
    position: relative;
    width: 40px;
    height: 40px;
    margin: 0 auto;
    
    .preview-btn {
      position: absolute;
      right: -10px;
      bottom: -10px;
      opacity: 0;
      transition: opacity 0.3s;
    }
    
    &:hover .preview-btn {
      opacity: 1;
    }
  }

  .avatar-uploader {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar-container {
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    
    .preview-actions {
      margin-top: 10px;
    }
    
    .avatar-uploader-component {
      text-align: center;
      
      .avatar-preview {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
    }
  }

  .image-preview-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}
</style>
